package com.qf.controller;

import com.qf.business.entity.Course;
import com.qf.business.service.ICourseSevice;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@Controller
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private ICourseSevice courseSevice;

    @Value("${upload.path}")
    private String uploadPath;

    /**
     * 跳转到插入页面
     * @return
     */
    @RequestMapping("/toinsert")
    public String toInsert(){
        return "courseinsert";
    }

    /**
     * 课程列表
     * @return
     */
    @RequestMapping("/list")
    public String courseList(Model model){
        List<Course> course = courseSevice.list();
        model.addAttribute("courselist", course);
        return "courselist";
    }

    /**
     * 新增课程
     * @return
     */
    @RequestMapping("/insert")
    public String courseInsert(Course course, MultipartFile file){

        //上传
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists())
            uploadFile.mkdirs();
        //文件名称
        String filename = UUID.randomUUID().toString();

        try (
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(new File(uploadFile, filename));
        ){
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //将文件名称设置给实体类
        course.setFengmian(filename);
        course.setHasNumber(course.getMaxNumber());

        //保存课程信息
        courseSevice.save(course);
        //重定向回课程列表页
        return "redirect:/course/list";
    }

    /**
     * 获取课程封面的图片
     */
    @RequestMapping("/getfengmian")
    public void getCourseFengmian(String fengmian, HttpServletResponse response){

        try (
                InputStream in = new FileInputStream(new File(uploadPath, fengmian));
                OutputStream out = response.getOutputStream();
        ) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改选课状态
     */
    @RequestMapping("/updateStatus")
    @ResponseBody
    public String updateStatus(Course course){
        course.setCreateTime(null);
        //调用service修改状态
        boolean flag = courseSevice.updateById(course);
        return "{\"result\":" + flag + "}";
    }
}
